package com.topera.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.topera.eduservice.entity.EduSubject;
import com.topera.eduservice.entity.excel.SubjectData;
import com.topera.eduservice.service.EduSubjectService;

public class SubjectListener extends AnalysisEventListener<SubjectData> {

    //因为SubjectListener不能交给Spring管理 需要自己new

    private EduSubjectService subjectService;

    public SubjectListener() {
    }

    public SubjectListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //一行一行的读取
    @Override
    public void invoke(SubjectData data, AnalysisContext analysisContext) {

        if(data==null){
           //抛出一个自定义异常
            throw new IllegalArgumentException("参数异常");
        }

        //一行一行读取 第一个值是一级分类  第二个值是二级分类
        String oneSubjectName = data.getOneSubjectName();//一级分类
        String twoSubjectName = data.getTwoSubjectName();//二级分类
        EduSubject oneSubject = existsOneSubject(subjectService,oneSubjectName);
        if(oneSubject==null){//没有才添加
            //添加操作
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(oneSubjectName);
            subjectService.save(oneSubject);

        }

        String pid = oneSubject.getId();

        //判断二级分类是否重复
        EduSubject twoSubject = existsTwoSubject(subjectService,twoSubjectName,pid);
        if(twoSubject==null){//二级分类不重复才添加
            twoSubject = new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(twoSubjectName);
            subjectService.save(twoSubject);
        }


    }

    //判断一级分类不能重复添加
    private EduSubject existsOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
       return subjectService.getOne(wrapper);
    }

    //判断二级分类不能重复添加
    private EduSubject existsTwoSubject(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        return subjectService.getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {



    }
}
